mylinkfandomcom-20200214-history
PythonNote
=Python Learning Note= Installation * Official Site www.python.org * Alternative download click =Language Primer= ; Style Guide for Python Code http://www.python.org/dev/peps/pep-0008/ ; Free learning materials * Dive Into Python 2.x * Dive Into Python 3.x * Learn Python The Hard Way, 3rd Edition Main Method #!/usr/bin/python import os import sys def main(): pass if __name__ "__main__": exit(main()) Statement if statement * if * if else * if elif else loop statement * for i in range(... * for else (else clause is executed when for exhausts its option, see more) * while boolean with statement with open("x.txt") as f: data = f.read() #do something with data class controlled_execution: def __enter__(self): set things up return thing def __exit__(self, type, value, traceback): tear things down with controlled_execution() as thing: some code Decorators Classes class Employee: # static variable empCount = 0 def __init__(self, name, salary): # member variable self.name = name self.salary = salary Employee.empCount += 1 Inheritance class SubClassName (ParentClass1ParentClass2, ...): 'Optional class documentation string' class_suite #!/usr/bin/python class Parent: # define parent class parentAttr = 100 def __init__(self): print "Calling parent constructor" def parentMethod(self): print 'Calling parent method' def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print "Parent attribute :", Parent.parentAttr class Child(Parent): # define child class def __init__(self): print "Calling child constructor" def childMethod(self): print 'Calling child method' class Person: pass class Child(Person): pass ppl = Person() child = Child(); print(issubclass(Child, Person)) print(isinstance(child, Person)) class Person: def __init__(self, name): pass class Child(Person): def __init__(self, name, age): Person.__init__(self, name) ppl = Person("Adam") child = Child("Bill", 10); print(issubclass(Child, Person)) print(isinstance(child, Person)) Methods * __repr__ Evaluatable string representation * __str__ Printable string representation * __cmp__ Object comparison, cmp(obj, x) * __del__ Destructor * __init__ Constructor * __add__ overloading '+' Reference * issubclass() * isinstance() * http://www.tutorialspoint.com/python/python_classes_objects.htm Pass by Object Reference Generator Polymorphism Lambda f = lambda x: x**2 + 2*x - 5 # f = function(x):return x**2 + 2*x - 5 lambda x: x % 3 0, 2, 3, 4, 5, 6, 7, 8, 9 mult3 = filter(lambda x: x % 3 0, 2, 3, 4, 5, 6, 7, 8, 9) def filterfunc(x): return x % 3 0 mult3 = filter(filterfunc, 2, 3, 4, 5, 6, 7, 8, 9) mult3 = for x in [1, 2, 3, 4, 5, 6, 7, 8, 9 if x % 3 0] def transform(n): return lambda x: x + n f = transform(3) Reference python=lambda-why Threading Posts a method to thread #!/usr/bin/python import thread import time # Define a function for the thread def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: pass Extends threading.Thread #!/usr/bin/python import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name print_time(self.name, self.counter, 5) print "Exiting " + self.name def print_time(threadName, delay, counter): while counter: if exitFlag: thread.exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() print "Exiting Main Thread" Lock and Queue queueLock = threading.Lock() workQueue = Queue.Queue(10) #lock queueLock.acquire() #do something with the workQueue if not workQueue.empty() workQueue.get() #unlock queueLock.release() Reference http://www.tutorialspoint.com/python/python_multithreading.htm =Object Oriented Programming= Goals * Robustness * Adaptability * Reusability Principles * Modularity * Abstraction * Encapsulation Reference * Learning Note: Object Oriented Programming * The End Of Object Inheritance & The Beginning Of A New Modularity, Google 2013 Design ; CRC Class-Responsibility-Collaborator * Responsibilities * Independence * Behaviors ; p83 Recursion Amortization Divide-and-conquer Prune-and-search/decrease-and-conquer Brute force Dynamic programming The greedy method Iterator Adapter Position Composition Template method Locator Factory method Namespace =Algorithm= * Constant 1 * Logarithm logn * Linear n * n-log-n nlogn * Quadratic n^2 * Cubic n^3 * Exponential a^n =Data Structure= Tuple Dictionary Lists Set Array Based Sequences Stack Queue Deque Priority Queue Linked List Tree =Cook Book= Regular Expression #list directory, split ...file-name in file-name names = os.listdir(sys.argv1) pattern = "(\.*\)" for line in names: m = re.search(pattern, line) subs = re.split(pattern, line) print(line) for sub in subs: if sub != None and len(sub) > 0: print(" %s" % (sub)) Reference * http://www.pythonregex.com/ * http://www.tutorialspoint.com/python/python_reg_expressions.htm File IO #read user raw input str = raw_input("Enter your input: "); # read user input, calculate python-express/statement into result as input # Enter your input: for x in range(2,10,2) # Recieved input is : 20, 30, 40 str = input("Enter your input: "); #!/usr/bin/python # Open a file # write and binary mode fo = open("/tmp/foo.txt", "wb") fo.write( "some string\n"); # Close opend file fo.close() Reference http://www.tutorialspoint.com/python/python_files_io.htm Database Sqlite3 #import the sqlite3 module import sqlite3 #open or create database db = sqlite3.connect("used.db") #sql statement cmd = "select user_id, user_name from ..." #query for row in db.execute(cmd): userId = row0 userName = row1 ... #close db db.close() MySQL sudo apt-get install python-mysqldb #!/usr/bin/python import _mysql import sys try: con = _mysql.connect('localhost', 'testuser', 'test623', 'testdb') con.query("SELECT VERSION()") result = con.use_result() print "MySQL version: %s" % \ result.fetch_row()0 except _mysql.Error, e: print "Error %d: %s" % (e.args0, e.args1) sys.exit(1) finally: if con: con.close() #!/usr/bin/python #http://pypi.python.org/pypi/MySQL-python/ import MySQLdb db = MySQLdb.connect(host="localhost", # your host, usually localhost user="john", # your username passwd="megajonhy", # your password db="jonhydb") # name of the data base # you must create a Cursor object. It will let # you execute all the query you need cur = db.cursor() # Use all the SQL you like cur.execute("SELECT * FROM YOUR_TABLE_NAME") # print all the first cell of all the rows for row in cur.fetchall() : print row0 * Python MySQL Database Access click XML SAX * read only * parse while reading * never store the while file DOM * parse the while file into DOM tree * editable lxml # ubuntu sudo apt-get install libxml2-dev libxslt1-dev sudo apt-get install python-lxml # mac python get-pip.py --user --no-setuptools --no-wheel pip install lxml brew install libxml2 brew install libxslt brew link libxml2 --force brew link libxslt --force ; lxml api _Element _ElementTree ; win32 click Spreadsheet xlwt import xlwt wb = Workbook() ws = wb.add_sheet("Sheet1") ws.write(rowNum, colNum, cellValue) #... wb.save("file-path-name.xls") openpyxl * http://openpyxl.readthedocs.org/en/latest/ Template Engine Django from django.template import Template, Context from django.conf import settings settings.configure() t = Template('My name is .') c = Context({'my_name': 'Daryl Spitzer'}) t.render© Jinja2 REST and SOAP * list of rest modules click * requests click * urllib2 build-in module, only supports GET and POST ** Missing manual click ** hack way for PUT method import urllib2 opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('http://example.org', data='your_put_data') request.add_header('Content-Type', 'your/contenttype') request.get_method = lambda: 'PUT' url = opener.open(request) Testing Framework unittest import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def test_shuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) # should raise an exception for an immutable sequence self.assertRaises(TypeError, random.shuffle, (1,2,3)) def test_choice(self): element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ '__main__': unittest.main() Reference click =Reference= * Tkinter http://www.tutorialspoint.com/python/python_gui_programming.htm =Links= * http://www.lfd.uci.edu/~gohlke/pythonlibs/